import {
	Editor,
	Toolbar
} from '@wangeditor/editor-for-vue'
export default {
	name: 'add',
	components: {
		VueNeditorWrap: () => import('../../../component/vue-neditor/lib/index.vue'),
		cityDialogCompnent: () => import('../cityDialog/cityDialog.vue'),
		Editor,
		Toolbar
	},
	data() {
		return {
			manage: '',
			model: {
				noticeid: '',
				title: '',
				city: '',
				cityname: '', //城市名称
				accessoryid: '',
				url: '',
				content: '',
			},
			editor: {
				customConfig: {
					uploadImgServer: '/system/v1/common/upload',
				},
			},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {
					uploadImage: {
						server: '/system/v1/common/fileUpload',
						fieldName: 'filecontent',
						maxFileSize: 5 * 1024 * 1024,
						// MaxFileLength: 50,
						// showBase64:true,
						// maxNumberOfFiles: 3,
						allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png'],
						onSuccess(file, res) {},
						onFailed(file, res) {
							console.log(`${file.name} 上传失败`, res);
							localStorage.setItem('url', res.data.fileurl)
						},
						customInsert(res, insertFn) {
							// 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
							// 先关闭等待的Message
							localStorage.setItem('url', res.data.fileurl)
							console.log(res);
							console.log(this);

							setTimeout(() => {
								insertFn(res.data.fileurl, res.data.fileurl);
							}, 1500)
						},
					},
				}

			},
			toolbarConfig: {},
			mode: 'default', // or 'simple'
			title: "",
			link: '2', // 默认展示 '自定义'
			imgUrl: '', //图片base64编码
			uploadForm: {
				filetype: '',
				filecontent: ''
			},
			myConfig: {
				// 如果需要上传功能,找后端小伙伴要服务器接口地址
				serverUrl: '/system/v1/common/upload',
				// 你的UEditor资源存放的路径,相对于打包后的index.html
				UEDITOR_HOME_URL: './assets/NEditor/',
				// 编辑器不自动被内容撑高
				autoHeightEnabled: false,
				// 初始容器高度
				initialFrameHeight: 240,
				// 初始容器宽度
				initialFrameWidth: '100%',
				// 关闭自动保存
				enableAutoSave: false
			},
			isVisible: false,
			isTip: false,
			isCheckbox: true,
			city: []
		}
	},
	created() {
		this.manage = this.$route.params.manage;
		if (this.manage === '编辑') {
			this.getData();
		}
	},

	beforeDestroy() {
		const editor = this.editor
		if (editor == null) return
		editor.destroy() // 组件销毁时，及时销毁编辑器
	},
	methods: {

		onChanges(data) {
			console.log(data);
		},
		onCreated(editor) {
			this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
		},
		getData() {
			let data = JSON.parse(localStorage.getItem('bannerData'));
			this.model = {
				...data
			};
			if (this.model.url) {
				this.model.content = "";
			}
		},
		// 显示城市选择dialog
		showCityDialog() {
			this.city = [];
			if (this.model.city && this.model.cityname) {
				let cityData = this.model.city;
				let cityNameData = this.model.cityname;
				if (cityData.indexOf(';') > -1 && cityNameData.indexOf(';') > -1) {
					let cityDataArr = cityData.split(';');
					let cityNameDataArr = cityNameData.split(';');
					cityDataArr.forEach((el, index) => {
						let obj = {};
						obj.code = el;
						obj.name = cityNameDataArr[index];
						this.city.push(obj);
					});
				} else {
					let obj = {};
					obj.code = cityData;
					obj.name = cityNameData;
					this.city.push(obj);
				}
			}
			this.isVisible = true;
		},
		// 处理城市数据
		getSelectCity(val) {
			let itemCity = [];
			let itemName = [];
			for (let i = 0; i < val.length; i++) {
				itemCity.push(val[i].code);
				itemName.push(val[i].name);
			}
			this.model.city = itemCity.join(';');
			this.model.cityname = itemName.join(';');
		},
		closeDialog(val) {
			this.isVisible = val;
		},
		handleCity(cityData) {
			let itemCity = [];
			let itemName = [];
			for (let i = 0; i < cityData.length; i++) {
				itemCity.push(cityData[i].code);
				itemName.push(cityData[i].name);
			}
			this.model.city = itemCity.join(';');
			this.model.cityname = itemName.join(';');
		},
		//导出pdf
		getBase64Image(url = "") {
			if (!url) return;
			let link = url;
			link = link.split("118.190.75.53");
			if (link.length > 1) link = link[1];
			var that = this;
			var image = new Image();
			console.log(url, "url");
			image.src = link + "?v=" + Math.random(); // 处理缓存
			image.crossOrigin = "*"; // 支持跨域图片
			image.onload = function() {
				that.model.accessoryid = that.drawBase64Image(image);
				console.log(that.model.accessoryid);
		 };
			return that.logo
		},
		drawBase64Image(img) {
			var canvas = document.createElement("canvas");
			canvas.width = img.width;
		 canvas.height = img.height;
			var ctx = canvas.getContext("2d");
			ctx.drawImage(img, 0, 0, img.width, img.height);
			var dataURL = canvas.toDataURL("image/png");
			return dataURL;

		},


		// 上传图片
		upload() {
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data'
				} //添加请求头
			};
			let uploadFile = this.$refs.file_ipt.files[0]; // 文件对象
			let filetype = (uploadFile.name.split('.')[1]).toLocaleLowerCase() // 文件后缀名
			if (filetype === 'png' || filetype === 'jpeg' || filetype === 'jpg') {
				let reader = new FileReader();
				reader.readAsDataURL(uploadFile);
				reader.onload = () => {
					let base64 = reader.result; // base64就是图片的转换的结果
					var img = new Image();
					img.src = base64;
					img.onload = () => {
						if (img.width / img.height == 2.5) {
							let param = new FormData(); //创建form对象
							param.append('filecontent', uploadFile);
							param.append('filetype', filetype);
							this.$axios.post("/system/v1/common/fileUpload", param, config).then(resp => {
								let that = this
								if (resp.data.message === 'success.') {
									setInterval(function() {
										that.imgUrl = resp.data.data.fileurl;
										that.model.accessoryid = resp.data.data.fileurl;
									}, 1000)
								}
							})
						} else {
							this.$message({
								message: '建议上传图片尺寸为5:2，请重新选择文件',
								type: 'warning'
							});
						}
					}
				}
			} else {
				this.$message({
					message: '上传文件格式不正确，请重新上传',
					type: 'warning'
				});
			}
		},
		// tab切换
		handleClick(val) {
			this.link = val;
		},
		// 获取和设置富文本内容
		ready(editorInstance) {
			// editorInstance.setContent(this.model.content);
			editorInstance.addListener('contentChange', () => {
				this.model.content = editorInstance.getContent();
			})
		},
		//取消
		concal() {
			this.$router.push({
				name: "bannerList"
			})
		},
		//确定
		submit() {
			console.log(this.model)
			if (this.model.title && this.model.city && this.model.accessoryid && (this.model.content || this.model
				.url)) {
				if (this.model.content && this.model.url) {
					this.$message({
						message: '链接和自定义内容不能同时录入',
						type: 'warning'
					});
				} else {
					this.$confirm(`是否确定${this.manage}该banner?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						this.$axios.post("/app/v1/platform/banner/updateAndInsert", this.model).then(resp => {

							if (resp.data.code === 1) {
								if (this.manage === '新增') {
									this.$message({
										message: '新增成功',
										type: 'success'
									});
								} else if (this.manage === '编辑') {
									this.$message({
										message: '编辑成功',
										type: 'success'
									});
								}
								this.$router.push({
									name: "bannerList"
								})
							} else {
								this.$message.warning(resp.data.message)
							}
						})
					}).catch(() => {
						this.$message({
							type: 'warning',
							message: '已取消该操作'
						});
					});
				}
			} else {
				this.$message({
					message: '请完善信息后再提交',
					type: 'warning'
				});
			}

		}
	}

}
